<template>
  <div class="p-20 bg-gray-1 border-box h-full w-full over-auto">
    <div class="mb-10 flex justify-between">
      <div class="nav">
        <div class="breadcrumb">
          <el-breadcrumb>
            <el-breadcrumb-item :to="{ path: 'fillInList' }"
              ><span class="breadcrumb-title">列表</span></el-breadcrumb-item
            >
            <el-breadcrumb-item>填报</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
      </div>
    </div>
    <div class="bg-white border-box fill-table" style="position: relative">
      <el-tabs
        style="padding: 0 20px"
        class="tabs"
        v-model="activeTabId"
        @tab-click="handleChangeTab"
      >
        <el-tab-pane
          v-for="(item, index) in tabsList"
          :key="index"
          :name="item.id"
        >
          <template #label>
            <span>
              {{ item.name }}({{ item.count ?? 0 }}/{{
                item.allCount ?? 0
              }})</span
            >
          </template>
        </el-tab-pane>
      </el-tabs>
      <div
        class="status-content"
        v-if="fillStatus == '1' || fillStatus == '-1'"
        :style="{
          color: getStatusInfo(fillStatus).color,
        }"
      >
        {{ fillStatus == '1' ? '退回' : '通过' }}：{{ taskDetail.applyCause }}
        <i class="el-icon el-icon-arrow-right" @click="handleStepClick"></i>
      </div>
      <div class="middle-content">
        <div
          class="p-20"
          style="padding-top: 0"
          v-for="(item, index) in renderData"
          :key="index"
        >
          <div class="flex justify-between items-center pb-10">
            <div
              class="content-title"
              :id="getAnchorIdByName(item.dimensionName)"
            >
              <!--              <svg-icon icon-class="视角" />-->
              <i class="title-icon"></i>
              <span>{{ item.dimensionName }}</span>
            </div>
            <div></div>
          </div>
          <template v-for="(child, idx) in item.items">
            <div
              class="content-title"
              :key="'view' + idx"
              v-if="child.indexResultInfos.length"
            >
              <svg-icon icon-class="标题图标" />
              <span>{{ child.viewName }}</span>
            </div>
            <el-table
              v-if="child.indexResultInfos.length"
              :key="'table' + idx"
              :data="child.indexResultInfos"
              class="border"
              stripe
              ref="tableRef"
            >
              <el-table-column
                type="index"
                label="序号"
                width="80"
                align="center"
              >
              </el-table-column>
              <el-table-column label="指标名称" width="120" align="center">
                <template slot-scope="scope">
                  <div class="flex justify-center">
                    {{ scope.row.indexName }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="指标类型" width="100" align="left">
                <template #default="scope">
                  {{ scope.row.type === 'base' ? '基本指标' : '特色指标' }}
                </template>
              </el-table-column>
              <el-table-column label="指标释义" align="left">
                <template slot-scope="scope">
                  <el-tooltip class="item" effect="dark" placement="top">
                    <div
                      v-html="scope.row.indexInformationRel.indexParaphrase"
                      slot="content"
                    ></div>
                    <div class="sl">
                      {{ scope.row.indexInformationRel.indexParaphrase }}
                    </div>
                  </el-tooltip>
                </template>
              </el-table-column>
              <el-table-column label="指标值" width="200" align="center">
                <template slot-scope="scope">
                  <div class="flex justify-center items-center">
                    <!--                      v-if="!!scope.row.indexDataRelVos.length"-->

                    <template v-if="!scope.row.indexFormulaRels.length">
                      <el-input
                        :disabled="!isEdit"
                        v-model.trim="scope.row.indexScore"
                        size="small"
                        style="width: 150px"
                        type="number"
                      ></el-input>
                    </template>
                    <template v-else>
                      <el-input
                        :disabled="true"
                        :value="getScoreValue(scope.row)"
                        placeholder="根据指标项计算"
                        size="small"
                        style="width: 150px"
                        type="number"
                      ></el-input>
                    </template>
                    {{ scope.row.indexInformationRel.indexUnit }}
                  </div>
                </template>
              </el-table-column>
              <!--              <el-input-->
              <!--                  :disabled="!isEdit || !!scope.row.indexFormulaRels.length"-->
              <!--                  v-model.trim="scope.row.indexScore"-->
              <!--                  :placeholder="-->
              <!--                        !scope.row.indexFormulaRels.length-->
              <!--                          ? ''-->
              <!--                          : '根据指标项计算'-->
              <!--                      "-->
              <!--                  size="small"-->
              <!--                  style="width: 150px"-->
              <!--                  type="number"-->
              <!--              ></el-input-->
              <!--              >-->
              <el-table-column label="数据项" width="300" align="center">
                <template #default="scope">
                  <div class="flex" style="flex-direction: column">
                    <div
                      class="data-item"
                      :key="i"
                      v-for="(val, i) in scope.row.indexDataRelVos"
                    >
                      <span class="data-item-name">{{ val.dataItem }}:</span>
                      <el-input
                        type="number"
                        :disabled="!isEdit"
                        v-model.trim="val.dataValue"
                        size="small"
                        style="width: 160px"
                        @input="handleDataChange(scope.row, val)"
                      ></el-input
                      >{{ val.unit }}
                    </div>
                  </div>
                </template>
              </el-table-column>
              <!--              <el-table-column label="数据来源" align="center">-->
              <!--                <template slot-scope="scope">-->
              <!--                  <div class="flex justify-center items-center">-->
              <!--                    &lt;!&ndash;                    v-if="!!scope.row.indexDataRelVos.length"&ndash;&gt;-->

              <!--                    <el-input-->
              <!--                      :disabled="!isEdit"-->
              <!--                      v-model.trim="scope.row.remark"-->
              <!--                      size="small"-->
              <!--                      type="textarea"-->
              <!--                    ></el-input>-->
              <!--                  </div>-->
              <!--                </template>-->
              <!--              </el-table-column>-->
            </el-table>
          </template>
        </div>
      </div>
      <div class="flex justify-center p-20 border-top">
        <el-button v-loading="loading" size="small" @click="goBack"
          >返回</el-button
        >
        <el-button
          v-loading="loading"
          type="primary"
          size="small"
          v-if="
            fillStatus != '2' &&
            fillStatus != '-1' &&
            currentUser?.hasPermission(PERMISSIONS.数据填报保存) &&
            isEdit
          "
          @click="handleSave(0)"
          >{{ currentUser?.getButtonName(PERMISSIONS.数据填报保存) }}</el-button
        >
        <el-button
          v-loading="loading"
          type="primary"
          size="small"
          v-if="
            fillStatus != '2' &&
            fillStatus != '-1' &&
            currentUser?.hasPermission(PERMISSIONS.数据填报提交) &&
            isEdit
          "
          @click="handleSave(2)"
          >{{ currentUser?.getButtonName(PERMISSIONS.数据填报提交) }}</el-button
        >
        <el-button
          v-if="
            fillStatus == '2' &&
            currentUser?.hasPermission(PERMISSIONS.数据填报通过)
          "
          type="primary"
          size="small"
          @click="handleApplyClick('-1')"
        >
          {{ currentUser?.getButtonName(PERMISSIONS.数据填报通过) }}
        </el-button>
        <el-button
          v-if="
            (fillStatus == '2' || fillStatus == '-1') &&
            currentUser?.hasPermission(PERMISSIONS.数据填报退回)
          "
          type="primary"
          size="small"
          @click="handleApplyClick('1')"
        >
          {{ currentUser?.getButtonName(PERMISSIONS.数据填报退回) }}
        </el-button>
      </div>
    </div>
    <el-dialog title="审核意见" :visible.sync="dialogVisible" width="30%">
      <el-form
        label-position="top"
        label-width="150px"
        :model="dialogForm"
        ref="baseFormRef"
        class="applyFormClass"
      >
        <el-form-item label="审核结果：" prop="applyStatus">
          <el-select v-model="dialogForm.applyStatus" disabled>
            <el-option label="通过" value="-1"> </el-option>
            <el-option label="退回" value="1"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="审核意见：" prop="applyCause">
          <el-input
            style="width: 100%"
            v-model="dialogForm.applyCause"
            :autosize="{ minRows: 2, maxRows: 4 }"
            type="textarea"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button
          v-loading="loading"
          type="primary"
          size="small"
          @click="dialogVisible = false"
          >取消</el-button
        >
        <el-button
          v-loading="loading"
          type="primary"
          size="small"
          @click="handleApply"
          plain
          >确认</el-button
        >
      </span>
    </el-dialog>
    <el-dialog
      title="审核流程"
      :visible.sync="applyDialogVisible"
      width="30%"
      class="apply-dialog"
    >
      <el-steps direction="vertical" :active="-1">
        <el-step
          v-for="(item, index) in applySteps"
          :key="index"
          :title="getStatusInfo(item.applyStatus).statusText"
          simple
        >
          <template #description>
            <div class="apply-content">
              <div>申请用户: {{ item.applyUserName }}</div>
              <div>申请理由: {{ item.applyCause }}</div>
              <div>申请时间: {{ item.applyTime }}</div>
            </div>
          </template>
        </el-step>
      </el-steps>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import {
  addOrUpdateResult,
  addTaskApply,
  queryOperation,
  queryResult,
  queryTaskApply,
  queryTotal,
} from '@api/city-index'
import { Message } from 'element-ui'
import { v4 } from 'uuid'
import { getStatusInfo } from '@u/ststus-color'
import { PERMISSIONS } from '@/common/user'
export default {
  name: 'fillInEdit',
  props: {},
  data() {
    return {
      PERMISSIONS,
      taskDetail: {},
      // 指标体系列表
      tableData: [],
      cols: [
        {
          prop: 'name',
          label: '指标名称',
        },
        {
          prop: 'introduction',
          label: '指标释义',
        },
      ],
      loading: false,
      pkid: '',
      taskId: '',
      regionId: '',
      isEdit: false,
      AUTH_TOKEN: null,
      fileList: [],
      desc: '',
      fillStatus: '',
      // 审核弹窗状态
      dialogVisible: false,
      dialogForm: {
        resourceId: '', //资源id
        applyStatus: '', //-1退回修改，0未审核，1通过
        applyCause: '', //审核理由
      },
      // 流程弹窗状态
      applyDialogVisible: false,
      applySteps: [],
      activeTabId: '',
      tabsList: [],
      renderData: [],
      operationData: [],
      anchorIds: {},
      isCq: false,
    }
  },
  mounted() {
    const pkid = this.$route.query.pkid
    const isEdit = this.$route.query.isEdit
    this.fillStatus = this.$route.query.fillStatus
    console.log(this.fillStatus)
    if (!pkid) {
      this.$router.push('fillInList')
    }
    this.pkid = pkid
    this.taskId = this.$route.query.taskId
    this.isEdit = typeof isEdit === 'string' ? isEdit === 'true' : isEdit
    // console.log('isEdit :>> ', typeof isEdit);
    const user = JSON.parse(window.localStorage.getItem('user'))
    const token = user && user.token
    if (token) {
      this.AUTH_TOKEN = token
    }
    this.regionId = this.$route.query.regionId
    this.dialogForm.resourceId = this.pkid
    // this.getDetail();
    // this.getApplySteps()
    this.getBaseData()
    this.getOperation()
    this.isCq = this.user.roleId === 'citymanager'
    this.getApplySteps()
  },
  methods: {
    getStatusInfo,
    getOperation() {
      queryOperation().then((res) => {
        if (res.success) {
          this.operationData = res.data
        }
      })
    },
    getScoreValue(row) {
      if (row.indexScore) {
        if (
          row.indexInformationRel.indexUnit === '%' ||
          row.indexInformationRel.indexUnit === '％'
        ) {
          return Number(row.indexScore) * 100
        } else {
          return row.indexScore
        }
      } else {
        return ''
      }
    },
    handleDataChange(row, val) {
      // console.log(row, val)
      const isCompeleted = row.indexDataRelVos.every((item) => !!item.dataValue)
      if (isCompeleted) {
        const formulas = row.indexFormulaRels
        let text = ''
        formulas.forEach((formula) => {
          if (formula.type === 'operate') {
            const t = this.operationData.find(
              (item) => item.pkid === formula.refId
            ).operate
            text += t
          } else {
            const t = row.indexDataRelVos.find(
              (item) => item.dataId === formula.refId
            ).dataValue
            text += t
          }
        })
        const result = eval(text)
        // 保留两位小数
        row.indexScore = result.toFixed(2)
      } else {
        row.indexScore = ''
      }
    },
    handleChangeTab() {
      document.querySelector('#' + this.activeTabId).scrollIntoView(true)
    },
    getAnchorIdByName(name) {
      // 获取uuid，并去除-，并随机截取6位
      if (this.anchorIds[name]) {
        return this.anchorIds[name]
      } else {
        const id = v4().replaceAll('-', '').slice(0, 6)
        this.anchorIds[name] = 'v' + id
        return this.anchorIds[name]
      }
    },
    mergeObjectsByProperty(arr, prop) {
      const result = {}

      arr.forEach((obj) => {
        const key = obj[prop]
        if (!result[key]) {
          result[key] = []
        }
        result[key].push(obj)
      })

      return Object.entries(result).map(([key, value]) => ({
        [prop]: key,
        items: value,
      }))
    },
    getBaseData() {
      queryTotal(this.taskId, this.regionId).then((totalRes) => {
        if (totalRes.success) {
          const totalList = totalRes.data
          queryResult(this.taskId, this.regionId).then((res) => {
            if (res.success) {
              // console.log(res.data)
              const list = this.mergeObjectsByProperty(
                res.data,
                'dimensionName'
              )

              this.tabsList = list.map((item) => {
                const countInfo = totalList.find(
                  (val) => val.dimensionName === item.dimensionName
                )
                return {
                  name: item.dimensionName,
                  count: countInfo?.completeCount,
                  allCount: countInfo?.allCount,
                  id: this.getAnchorIdByName(item.dimensionName),
                }
              })
              this.activeTabId = this.tabsList[0].id
              this.renderData = list
            }
          })
        } else {
          Message.error(totalRes.message)
        }
      })
    },
    getApplySteps() {
      queryTaskApply(this.dialogForm.resourceId).then((res) => {
        if (res.success) {
          // console.log(res.data)
          if (res.data.length) {
            this.taskDetail.applyCause = res.data[0].applyCause
          } else {
            this.taskDetail.applyCause = ''
          }
          this.applySteps = res.data
        }
      })
    },
    handleStepClick() {
      this.applyDialogVisible = true
      this.getApplySteps()
    },
    handleApplyClick(status) {
      this.dialogVisible = true
      this.dialogForm.applyStatus = status
    },
    handleApply() {
      addTaskApply(this.dialogForm).then((res) => {
        if (res.success) {
          this.$message.success('提交成功')
          this.dialogVisible = false
          this.$router.go(-1)
        }
      })
    },
    handleSave(status) {
      // console.log(status)
      // console.log(this.renderData)
      const data = []
      this.renderData.forEach((child) => {
        child.items.forEach((item) => {
          item.indexResultInfos.forEach((infomation) => {
            const info = infomation.indexDataRelVos.map((val) => {
              return {
                pkid: val.pkid,
                indexId: infomation.indexInformationRel.indexId,
                dataId: val.dataId,
                value: val.dataValue,
              }
            })
            const val = {
              dimensionName: child.dimensionName,
              viewName: item.viewName,
              indexName: infomation.indexName,
              examinationContent:
                infomation.indexInformationRel.indexParaphrase,
              indexScore: infomation.indexScore,
              regionId: this.regionId,
              taskId: this.taskId,
              type: infomation.type,
              templateId: item.templateId,
              orderIndex: infomation.orderIndex,
              dataInfos: info,
              // remark: infomation.remark,
              pkid: infomation.pkid,
            }
            // if (info.length) {
            data.push(val)
            // }
          })
        })
      })
      // console.log(data)
      addOrUpdateResult(data).then((res) => {
        // console.log(res)
        if (res.success) {
          addTaskApply({
            resourceId: this.pkid, //资源id
            applyStatus: status, //-1退回修改，0未审核，1通过
            applyCause: '', //审核理由
          }).then((val) => {
            if (val.success) {
              Message.success(res.data)
              this.$router.go(-1)
            } else {
              Message.error(res.data)
            }
          })
        } else {
          Message.error(res.message)
        }
      })
    },
    goBack() {
      this.$router.push('fillInList')
    },
  },
  computed: {
    ...mapGetters(['currentUser', 'user']),
  },
  watch: {},
}
</script>

<style lang="scss" scoped>
.circle {
  width: 6px;
  height: 6px;
}

.bg-blue {
  background: #10a6dd;
}

.bg-orange {
  background: #ff9f24;
}

.table-footer {
  text-align: right;
}

.gray {
  color: #778ca2;
  line-height: 2em;

  span {
    color: #252631;
  }
}

.w6 {
  width: 120px;
}

.sl {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}

.middle-content {
  height: calc(100% - 126px);
  overflow-y: auto;
}

.content-title {
  margin: 10px 0;
  padding: 0px 0 2px 5px;
  font-size: 14px;
  font-family: Microsoft YaHei;
  font-weight: bold;
  color: #000000;
  display: flex;
  align-items: center;

  > span {
    margin-left: 5px;
  }

  .title-icon {
    width: 5px;
    height: 16px;
    background: #10a6dd;
    border-radius: 3px;
    margin-right: 4px;
  }
}

.nav {
  height: 40px;
  border-radius: 2px;

  .breadcrumb {
    height: 40px;
    padding: 15px 0px 10px 0;
    box-sizing: border-box;

    &-title {
      position: relative;
      margin-left: 6px;
      height: 21px;
      font-size: 15px;

      &::before {
        content: '';
        width: 5px;
        height: 16px;
        background: #10a6dd;
        border-radius: 3px;
        margin-right: 4px;
        display: inline-block;
        position: absolute;
        top: 50%;
        left: -11px;
        transform: translateY(-50%);
      }
    }
  }
}

.tabs {
  // 去除a标签默认样式
  a {
    color: #333;
    text-decoration: none;
  }
}

.data-item {
  display: flex;
  //justify-content: space-between;
  align-items: center;
  margin-bottom: 6px;

  .data-item-name {
    width: 100px;
    text-align: right;
    margin-right: 6px;
  }
}

::v-deep {
  .el-tabs__nav-wrap::after {
    display: none;
  }
}

.applyFormClass {
  .el-form-item {
    margin-bottom: 0;
  }
}

.status-content {
  position: absolute;
  top: 16px;
  right: 20px;
  display: flex;
  align-items: center;

  .el-icon {
    cursor: pointer;
  }
}

.fill-table {
  height: calc(100% - 50px);
}
</style>
<style>
.apply-dialog {
  .el-dialog__body {
    max-height: 500px;
    overflow-y: auto;
    .el-step__title {
      color: rgb(92, 92, 92);
    }

    .el-step .el-step__line {
      left: 5px;
      top: 3px;
      bottom: -3px;
    }

    .el-step__icon {
      width: 12px;
      height: 12px;

      .el-step__icon-inner {
        display: none;
      }
    }

    .apply-content {
      color: rgb(147, 147, 147);
    }
  }
}
</style>
